<?php

namespace App\Admin\Controllers;

use DB;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Redis;
use App\Country;
use App\UserMatch;
use App\MatchLog;
use App\User;
use App\WxPublicUser;
use App\WorldChampion;
use App\Jobs\SendMessage;

class WorldcupController extends Controller
{
	/**
	 * [index 比赛列表]
	 * @return [type] [description]
	 */
	public function index(Request $request)
	{
		$datas = MatchLog::where('id', '>', 0);
		if ($request->input('time')) {
			$period = $request->input('time');
			$time_arr = explode('~', $request->input('time'));
			$begin = strtotime($time_arr[0]);
			$end = strtotime($time_arr[1]);
			$datas = $datas->whereBetween('match_time', [$begin, $end]);
		}
		$datas = $datas->orderBy('match_time', 'ASC')->paginate(15);
		$datas->appends([
			'time' => $request->input('time')
			]);
		$country_arr = Country::select(DB::raw('id, name'))->get()->toArray();
		$country_arr = array_pluck($country_arr, 'name', 'id');
		return view('admin.worldcup.index', compact('datas', 'country_arr'));
	}

	/**
	 * [create description]
	 * @return [type] [description]
	 */
	public function create()
	{
		$countrys = Country::get();
		return view('admin.worldcup.add', compact('countrys'));
	}

	/**
	 * [store 新增]
	 * @return [type] [description]
	 */
	public function store(Request $request)
	{
    	$validator = Validator::make($request->all(), [
			'home' => 'required',
            'away' => 'required',
            'level' => 'required',
            'match_time' => 'required'
        ], [
        	'home.required' => '请选择主队',
        	'away.required' => '请选择客队',
        	'level.required' => '请选择级别',
        	'match_time.required' => '请选择比赛时间',
        ]);
        if ($request->input('home') == $request->input('away')) {
	    	$validator->after(function($validator){
	            $validator->errors()->add('home', '主客队不能相同');
	        });	
        }
        if ($validator->passes()) {
        	$match = new MatchLog;
        	$match->home = $request->input('home');
        	$home_name = Country::where(['id' => $request->input('home')])->first()->name;
        	$match->home_name = $home_name;
        	$match->away = $request->input('away');
        	$away_name = Country::where(['id' => $request->input('away')])->first()->name;
        	$match->away_name = $away_name;
        	$match->level = $request->input('level');
        	$match->match_time = strtotime($request->input('match_time'));
        	$match->save();

            return ['flag' => true, 'msg' => '创建成功'];
        } else {
            return $validator->errors();
        }
	}

	/**
	 * [edit description]
	 * @return [type] [description]
	 */
	public function edit(MatchLog $match)
	{
		$countrys = Country::get();
		return view('admin.worldcup.edit', compact('match', 'countrys'));
	}

	/**
	 * [restore description]
	 * @param  MatchLog $match   [description]
	 * @param  Request  $request [description]
	 * @return [type]            [description]
	 */
	public function restore(MatchLog $match, Request $request)
	{
    	$validator = Validator::make($request->all(), [
			'home' => 'required',
            'away' => 'required',
            'level' => 'required',
            'match_time' => 'required'
        ], [
        	'home.required' => '请选择主队',
        	'away.required' => '请选择客队',
        	'level.required' => '请选择级别',
        	'match_time.required' => '请选择比赛时间',
        ]);
        if ($request->input('home') == $request->input('away')) {
	    	$validator->after(function($validator){
	            $validator->errors()->add('home', '主客队不能相同');
	        });	
        }
        if ($validator->passes()) {
        	$match->home = $request->input('home');
        	$home_name = Country::where(['id' => $request->input('home')])->first()->name;
        	$match->home_name = $home_name;
        	$match->away = $request->input('away');
        	$away_name = Country::where(['id' => $request->input('away')])->first()->name;
        	$match->away_name = $away_name;
        	$match->level = $request->input('level');
        	$match->match_time = strtotime($request->input('match_time'));
        	$match->save();

            return ['flag' => true, 'msg' => '编辑成功'];
        } else {
            return $validator->errors();
        }
	}

	/**
	 * [result 发放奖励]
	 * @param  MatchLog $match [description]
	 * @return [type]          [description]
	 */
	public function result(MatchLog $match)
	{
		return view('admin.worldcup.result', compact('match'));
	}

	/**
	 * [sendResult 发放奖励]
	 * @param  MatchLog $match   [description]
	 * @param  Request  $request [description]
	 * @return [type]            [description]
	 */
	public function sendResult(MatchLog $match, Request $request)
	{
    	$validator = Validator::make($request->all(), [
			'match_result' => 'required'
        ], [
        	'match_result.required' => '请选择比赛结果'
        ]);
    	$home = Country::where(['id' => $match->home])->first()->name;
    	$away = Country::where(['id' => $match->away])->first()->name;
    	$re_arr = [1 => $home.'胜', 2 => $away.'胜', 3 => '平局'];
        if ($validator->passes()) {
        	$match->match_result = $request->input('match_result');
        	$match->status = 1;
        	$match->save();
        	$result = $re_arr[$match->match_result];
        	$users = $match->winNum;
        	if ($users) {
        		Redis::del("wordcup_winner_list");
        		foreach ($users as $user) {
        			$user->status = 1;
        			$user->save();
        			$user = User::where(['userid' => $user->userid])->first();
        			$user->gems += $match->reward;
        			$user->save();
        			$wx_user = WxPublicUser::where(['unionid' => substr($user->account, 3)])->first();
        			if ($wx_user) {
        				//oAJ3R015p89GhAjdj-f5IcheeOkw
	        			$username = $user->nickname ? $user->nickname : base64_decode($user->name);
	        			$data = ['userid' => $user->userid, 'username' => $username, 'openid' => $wx_user->openid, 'result' => $result, 'reward' => $match->reward, 'team' => $home.' vs '.$away];
	        			$data = json_encode($data);
	        			Redis::lpush("wordcup_winner_list", $data);
        			}
        		}	
        	}

            return ['flag' => true, 'msg' => '开始发放'];
        } else {
            return $validator->errors();
        }
	}

	/**
	 * [beginGuess description]
	 * @return [type] [description]
	 */
	public function beginGuess(MatchLog $match)
	{
		$match->update(['status' => 2]);
		return back();
	}

	/**
	 * [editMatch description]
	 * @return [type] [description]
	 */
	public function editMatch(MatchLog $match)
	{
		return view("admin.worldcup.editReward", compact("match"));
	}

	/**
	 * [storeReward description]
	 * @return [type] [description]
	 */
	public function storeReward(MatchLog $match, Request $request)
	{
		$match->reward = $request->input("reward");
		$match->save();
		return ['flag' => true, 'msg' => "设置成功"];
	}

	/**
	 * [sendVoice 消息通知]
	 * @return [type] [description]
	 */
	public function sendVoice()
	{
		system("php /home/www/leyougame/artisan send:reward", $retval);
		if ($retval == 0) {//命令执行成功
			return view("admin.worldcup.voice");
		}
	}

	/**
	 * [endMsg description]
	 * @return [type] [description]
	 */
	public function endMsg()
	{
		$len = Redis::lLen('wordcup_winner_list');
		if ($len > 0) {
			return ['flag' => false];
		} else {
			return ['flag' => true];
		}
	}

	/**
	 * [champion 冠军竞猜]
	 * @return [type] [description]
	 */
	public function champion()
	{
		$num = WorldChampion::get()->count();
		return view('admin.worldcup.champion', compact('num'));
	}

	/**
	 * [ptcpDetail 竞猜人员详情]
	 * @return [type] [description]
	 */
	public function ptcpDetail(MatchLog $match)
	{
		$games = UserMatch::where(['match_id' => $match->id])->get();
		return view('admin.worldcup.ptcpDetail', compact('games'));
	}

	/**
	 * [winDetail 获奖人员详情]
	 * @return [type] [description]
	 */
	public function winDetail(MatchLog $match)
	{
		$games = UserMatch::where(['match_id' => $match->id, 'result' => $match->match_result])->get();
		return view('admin.worldcup.winDetail', compact('games'));
	}

	/**
	 * [championMessage 世界杯消息]
	 * @return [type] [description]
	 */
	public function championMessage()
	{
		dispatch(new SendMessage());
		return view('admin.worldcup.championMsg');
	}

	/**
	 * [championMsgEnd 消息发送完毕]
	 * @return [type] [description]
	 */
	public function championMsgEnd()
	{
		if (Redis::keys('finish')) {
			return ['flag' => true];
		}
		return ['flag' => false];
	}
}	